package com.hserver.docker.service.impl;

import com.hserver.docker.bean.Deploy;
import com.hserver.docker.config.ConstConfig;
import com.hserver.docker.service.GitService;
import com.hserver.docker.service.LogService;
import com.hserver.docker.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Bean;

import java.io.File;

/**
 * @author hxm
 */
@Slf4j
@Bean
public class GitServiceImpl implements GitService {


    @Autowired
    private LogService logService;

    @Override
    public Boolean cloneProject(Deploy deploy,String recordId) {
        log.debug("git clone start");
        logService.add(recordId,"移除旧代码");
        FileUtil.deleteFolder(ConstConfig.PROJECT_PATH+deploy.getUuid());
        logService.add(recordId,"开始拉取仓库代码");
        UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =null;
        if (deploy.getPassword()!=null&&deploy.getPassword()!=null) {
            usernamePasswordCredentialsProvider = new
                    UsernamePasswordCredentialsProvider(deploy.getUserName(), deploy.getPassword());
        }
        //克隆代码库命令
        CloneCommand cloneCommand = Git.cloneRepository();
        try {
           cloneCommand.setURI(deploy.getUrl())
                    .setBranch(deploy.getBranch())
                    .setDirectory(new File(ConstConfig.PROJECT_PATH+deploy.getUuid()))
                    .setCredentialsProvider(usernamePasswordCredentialsProvider)
                    .call()
                   .close();
            logService.add(recordId,"仓库代码拉取完成");
            return true;
        } catch (GitAPIException e) {
            e.printStackTrace();
            logService.add(recordId,"仓库代码拉取异常");
            logService.add(recordId,e.getMessage());
            logService.add(recordId,e.getLocalizedMessage());
            return false;
        }
    }
}
